package com.book.bigwork.Webcontroller;

import com.book.bigwork.Webservice.UserService;
import com.book.bigwork.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Order;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;

@Controller
public class UserController {
    private final UserService userService;
    private final OrderService orderService;

    @Autowired
    public UserController(UserService userService, OrderService orderService) {
        this.userService = userService;
        this.orderService = orderService;
    }

    @GetMapping("/login")
    public String login(Principal principal) {
        if (principal == null) {
            return "/login";
        }
        return "redirect:/home";
    }

    @GetMapping("/registration")
    public String registration(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "registration";
    }

    @PostMapping("/registration")
    public String createUser(@Valid User user, BindingResult bindingResult,
                             Model model) {
        User newUser = userService.findUserByName(user.getUserName());
        if (newUser != null) {
            bindingResult.rejectValue("userName", "error.user","用户已经存在");
        }
        if (!bindingResult.hasErrors()) {
            userService.registerUser(user);
            model.addAttribute("successMessage", "用户注册成功");
            model.addAttribute("user", new User());
        }
        return "registration";
    }

    @PostMapping("/users")
    @Secured ("ROLE_ADMIN")
    public String createUser(@RequestBody User user, Model model) {
        if (user.getUserId() != 0) {
            model.addAttribute("message", "用户存在");
        } else if (userService.findByUserName(user.getUserName()) != null) {
            model.addAttribute("message", "用户名存在");
        } else {
            userService.registerUser(user);
            model.addAttribute("message", "用户创建成功");
        }
        return "editUser";
    }

    @GetMapping("/profile")
    public String getCurrentUser(Principal principal, Model model) {
        if (principal == null) {
            return "redirect:/home";
        }
        User user = userService.findByUserName(principal.getName());
        model.addAttribute("user", user);
        return "profile";
    }

    @PostMapping("/profile")
    public String updateUser(@ModelAttribute User user,
                             BindingResult bindingResult,
                             Model model,
                             Principal principal) {
        User userExists = userService.findByUserName(user.getUserName());
        if (userExists != null && !Objects.equals(userExists.getUserName(),
                principal.getName())){
            bindingResult.rejectValue("userName", "error.user","用户名重复");
        }
        if (!bindingResult.hasErrors()) {
            userService.updateUser(user);
            model.addAttribute("successMessage", "用户信息更新成功");
        }
        return getCurrentUser(principal, model);
    }

    @GetMapping("users")
    @Secured ("ROLE_ADMIN")
    public String getUsers(Model model) {
        List<User> users = userService.findAllUsers();
        model.addAttribute("users", users);
        return "showAllUsers";
    }

    @GetMapping("/users/add")
    @Secured ("ROLE_ADMIN")
    public String addUserPage(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "addUser";
    }

    @PostMapping("/users/add")
    @Secured ("ROLE_ADMIN")
    public String addUser(@ModelAttribute User user, Model model, BindingResult
            bindingResult) {
        User userExists = userService.findByUserName(user.getUserName());
        if (userExists != null) {
            bindingResult.rejectValue("userName", "error.user","用户已存在");
        }
        if (!bindingResult.hasErrors()) {
            User newUser = userService.registerUser(user);
            model.addAttribute("successMessage", "用户创建 " + newUser.
                    getUserId());
            model.addAttribute("user", new User());
        }
        return "addUser";
    }

    @GetMapping("/users/edit/{userId}")
    @Secured ("ROLE_ADMIN")
    public String editUserPage(@PathVariable Long userId, Model model) {
        User user = userService.findUserById(userId);
        model.addAttribute("user", user);
        return "editUser";
    }

    @PostMapping("/users/edit")
    @Secured ("ROLE_ADMIN")
    public String editUser(@ModelAttribute User user, Model model) {
        userService.updateUser(user);
        model.addAttribute("successMessage", "用户更新 " + user.getUserId());
        return editUserPage(user.getUserId(), model);
    }

    @GetMapping("/users/delete/{userId}")
    @Secured ("ROLE_ADMIN")
    public String deleteUser(@PathVariable Long userId, Model model) {
        if (userService.getUserOrderAmount(userId)>0) {
            model.addAttribute("Message", "该用户名下有订单，不能删除");
        }else {
            userService.deleteUserById(userId);
            model.addAttribute("Message", "用户编号 " + userId + "删除成功");
        }
        return getUsers(model);
    }

    @GetMapping("/users/edit/{userId}/completeOrder/{orderId}")
    @Secured ("ROLE_ADMIN")
    public String completeOrder(@PathVariable Long orderId, @PathVariable Long
            userId, Model model) {
        Order order = orderService.findOrderById(orderId);
        order.setOrderStatus(true);
        orderService.updateOrder(order);
        model.addAttribute("successMessage", "订单编号 " + orderId + " 完成");
        return editUserPage(userId, model);
    }
    @GetMapping("/users/edit/{userId}/deleteOrder/{orderId}")
    @Secured ("ROLE_ADMIN")
    public String deleteOrder(@PathVariable Long orderId, @PathVariable Long
            userId, Model model) {
        Order order = orderService.findOrderById(orderId);
        orderService.deleteOrder(order);
        model.addAttribute("successMessage", "订单编号 " + orderId + "删除");
        return editUserPage(userId, model);
    }
}
